<?php
class MysqlDb{
	private $_host;//主机地址
	private $_user;//用户名
	private $_pwd;//密码
	private $_db;//数据库
	private $_char;//字符集
	private $_link;//连接
	private static $_instance;//实例
	//构造
	private function __construct($config=array()){
		$this->_init($config);
		$this->_connect();
		$this->_charset();
		$this->_dbset();
	}
	//克隆私有化
	private function __clone(){}
	//共有的获取实例的方法
	public static function getInstance(){
		if(!(isset(static::$_instance) && is_object(static::$_instance))){
			static::$_instance = new MysqlDb();
		}
		return static::$_instance;
	}
	//初始化属性
	private function _init($config=array()){
		$this->_host = isset($config['host'])?$config['host']:'localhost';
		$this->_user = isset($config['user'])?$config['user']:'root';
		$this->_pwd = isset($config['pwd'])?$config['pwd']:'root';
		$this->_db = isset($config['db'])?$config['db']:'mvc';
		$this->_char = isset($config['char'])?$config['char']:'utf8';
	}
	//连接
	private function _connect(){
		$link = @mysql_connect($this->_host,$this->_user,$this->_pwd);
		if($link){
			$this->_link = $link;
		}else{
			die('数据库连接失败，失败原因：'.mysql_error());
		}
	}
	//设置字符集
	private function _charset(){
		mysql_set_charset($this->_char);
	}
	//选择数据库
	private function _dbset(){
		mysql_select_db($this->_db);
	}
	//query
	public function query($sql){
		$res = mysql_query($sql);
		$return = array();
		if($res){
			while($row = mysql_fetch_assoc($res)){
				$return[] = $row;
			}
			mysql_free_result($res);
			return $return;
		}else{
			die('查询sql有误，语句为'.$sql.'错误原因：'.mysql_error());
		}
	}
	//exec
	public function exec($sql){
		$res = mysql_query($sql);
		if($res){
			return mysql_affected_rows();
		}else{
			die('增删改sql有误，语句为'.$sql.'错误原因：'.mysql_error());
		}
	}
	//关闭数据库
	public function __destruct(){
		mysql_close();
	}
}